package com.sunday.ble.orlant;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.le.ScanFilter;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelUuid;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.sunday.ble.orlant.activity.HistoryActivity;
import com.sunday.ble.orlant.bluetooth.LiteBleGattCallback;
import com.sunday.ble.orlant.bluetooth.LiteBluetooth;
import com.sunday.ble.orlant.bluetooth.conn.BleCharactCallback;
import com.sunday.ble.orlant.bluetooth.conn.LiteBleConnector;
import com.sunday.ble.orlant.bluetooth.exception.BleException;
import com.sunday.ble.orlant.bluetooth.log.BleLog;
import com.sunday.ble.orlant.bluetooth.scan.PeriodMacScanCallback;
import com.sunday.ble.orlant.event.DoOption;
import com.sunday.ble.orlant.greendao.Device;
import com.sunday.ble.orlant.greendao.DeviceDao;
import com.sunday.ble.orlant.utils.BluetoothDialogView;
import com.sunday.ble.orlant.utils.DeviceBytes;
import com.sunday.ble.orlant.utils.HomeWatcher;
import com.sunday.ble.orlant.utils.statusbar.StatusBarUtil;
import com.sunday.common.event.EventBus;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.common.widgets.UIAlertView;
import com.sunday.common.widgets.taosty.Toasty;
import com.sunday.member.base.BaseActivity;
import com.sunday.member.event.ExitApp;
import com.sunday.member.utils.SharePerferenceUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.dao.query.QueryBuilder;

import static android.Manifest.permission.ACCESS_COARSE_LOCATION;
import static android.Manifest.permission.READ_PHONE_STATE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import static android.content.pm.PackageManager.PERMISSION_GRANTED;

public class MainActivity extends BaseActivity {
    @Bind(R.id.img_right)
    ImageView imgRight;
    @Bind(R.id.img_logo)
    ImageView imgLogo;
    @Bind(R.id.light)
    ImageView light;
    @Bind(R.id.up)
    ImageView up;
    @Bind(R.id.kill)
    ImageView kill;
    @Bind(R.id.stop)
    ImageView stop;
    @Bind(R.id.anion)
    ImageView anion;
    @Bind(R.id.down)
    ImageView down;
    @Bind(R.id.convection)
    ImageView convection;
    @Bind(R.id.tvInfo)
    TextView tvInfo;
    @Bind(R.id.option)
    TextView option;
    @Bind(R.id.rMenu)
    RelativeLayout rMenu;
    private Activity activity;
    private BluetoothDevice mDevice;
    private BluetoothDialogView bluetoothDialogView;
    private int w,h;
    private RelativeLayout.LayoutParams relativeParams;
    private LinearLayout.LayoutParams linerParams;
    private List<BluetoothDevice> bluetoothDeviceList1 = new ArrayList<>();
    private HomeWatcher mHomeWatcher;

    /**
     * 蓝牙主要操作对象，建议单例。
     */
    private static LiteBluetooth liteBluetooth;
    private static String MAC = "00:00:00:AA:AA:AA";//设备mac
    public String UUID_SERVICE = "0000fff0-0000-1000-8000-00805f9b34fb";
    public String UUID_CHAR_WRITE = "0000fff6-0000-1000-8000-00805f9b34fb";
    private static String NOT_SCAN = "reScan";
    private static String DEVICE_CONNECTED = "1";//连接过
    private static String DEVICE_DISCONNECTED = "0";//未连接过
    private static int TIME_OUT_SCAN = 60000;
    private static final int CONNECT_LOADING = 1;//连接中
    private static final int CONNECT_SUCCESS = 2;//连接成功
    private static final int CONNECT_FAIL = -1;//连接失败
    private static final int CONNECT_STUDY = 3;//学习
    private static final int CONNECT_DEL = 4;//删除
    private static int CONNECT_TYPE;//连接类型，0：手动扫描连接，1：数据库直接连接
    private Map<String, BluetoothDevice> map = new ConcurrentHashMap<>();
    private static String TAG = MainActivity.class.getSimpleName();
    private static boolean isConnect;//是否连接
    private BluetoothDevice targetDevice;//连接的设备
    private Device dbLinkDevice;//数据库连接的设备
    private DeviceDao dao;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_menu);
        ButterKnife.bind(this);
        StatusBarUtil.setTransparentForImageView(this, null);
        activity = this;
        w = DeviceUtils.getDisplay(mContext).widthPixels;
        h = DeviceUtils.getDisplay(mContext).heightPixels;
        int navigation = DeviceBytes.getVirtualBarHeigh(mContext);
        Log.i("---virtualBarHeigh : ",""+navigation);
        if (navigation>0){
            h -= navigation;
        }
        initView();
        //检查权限
        if (Build.VERSION.SDK_INT >= 23) {
            check();
        } else {
            init();
        }
    }

    private void initBle(){
        if (liteBluetooth == null) {
            liteBluetooth = new LiteBluetooth(activity);
        }
        liteBluetooth.enableBluetoothIfDisabled(activity, 1);
    }

    private void init() {
        DeviceBytes.setMacAddress();
    }

    private boolean checkBlue(){
        if (Build.VERSION.SDK_INT < 18) return false;
        // 检查当前手机是否支持ble 蓝牙,如果不支持退出程序
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE))return false;
        return true;
    }

    private void addDevice(){
        if (isConnect && targetDevice!=null){
            Device macDevice = getDeviceByMac(MAC);
            if (macDevice==null){
                updateDeviceToDisConnect();
                Device device = new Device();
                device.setMac(targetDevice.getAddress());
                device.setName(targetDevice.getName()==null?"默认名称":targetDevice.getName());
                device.setField1("1");
                dao.insert(device);
                dbLinkDevice = device;
                Log.i(TAG," addDevice ："+device.getName()+"  "+device.getMac());
            }else {
                macDevice.setField1(DEVICE_CONNECTED);
                dao.update(macDevice);
            }
            deviceList.clear();
            deviceList.addAll(dao.loadAll());
        }
    }
    //get device by mac
    private Device getDeviceByMac(String mac){
        List<Device> macDevise = dao.queryBuilder().where(DeviceDao.Properties.Mac.eq(mac)).list();
        for (Device device : macDevise){
            if (mac.equals(device.getMac())){
                return device;
            }
        }
        return null;
    }
    //del device by mac
    private void delDeviceByMac(String mac){
        List<Device> macDevise = dao.queryBuilder().where(DeviceDao.Properties.Mac.eq(mac)).list();
        for (Device device : macDevise){
            if (mac.equals(device.getMac())){
                dao.delete(device);
            }
        }
    }
    private void updateDeviceByMac(String mac){
        List<Device> macDevise = dao.queryBuilder().where(DeviceDao.Properties.Mac.eq(mac)).list();
        for (Device device : macDevise){
            if (mac.equals(device.getMac())){
                device.setField1(DEVICE_DISCONNECTED);
                dao.update(device);
            }
        }
    }

    //将数据库中的所有设备设置为未连接状态
    private void updateDeviceToDisConnect(){
        List<Device> deviceList = dao.loadAll();
        for (Device device1 : deviceList){
            device1.setField1(DEVICE_DISCONNECTED);
            Log.i("   update : ",device1.getField1());
        }
        dao.updateInTx(deviceList);
    }

    public void startLeScan(final BluetoothAdapter.LeScanCallback callback) {
        liteBluetooth.getBluetoothAdapter().startLeScan(callback);
        //liteBluetooth.getBluetoothAdapter().startLeScan(new UUID[]{UUID.fromString(UUID_SERVICE)},callback);
    }

    private void initDialogView(){
        bluetoothDialogView = new BluetoothDialogView(mContext,"选择设备",bluetoothDeviceList1,adapterShowList);
        bluetoothDialogView.setClicklistener(new BluetoothDialogView.ClickListenerInterface() {
            @Override
            public void doConnect(BluetoothDevice device,Device device1) {
                initBle();
                if (device != null) {
                    dbLinkDevice = device1;
                    connect(device);
                    bluetoothDialogView.dismiss();
                    if (scanCallback!=null){
                        liteBluetooth.stopScan(scanCallback);
                        Log.i("---bluetoothDialogView","   stopScan(scanCallback)");
                    }
                    if (scanThenConnect!=null){
                        liteBluetooth.stopScan(scanThenConnect);
                        Log.i("---bluetoothDialogView","   stopScan(scanThenConnect)");
                    }
                }
            }
        });
        bluetoothDialogView.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                option.setText(isConnect?"断开":"连接");
                if (!isConnect) tvInfo.setText("未连接至设备");
                if (scanCallback!=null){
                    liteBluetooth.stopScan(scanCallback);
                    Log.i("---bluetoothDialogView","   stopScan(scanCallback)");
                }
            }
        });
    }

    private void showBles(){
        dissMissDialog();
        if (bluetoothDialogView==null){initDialogView();}
        if (bluetoothDialogView.isShowing()){
            Log.i("-----","bluetoothDialogView  isShowing");
            bluetoothDialogView.refreshAdapter(bluetoothDeviceList1,adapterShowList);
        }else {
            bluetoothDialogView.show();
        }
    }

    public void timeOut(){
        Log.i("---","搜索结束");
        dissMissDialog();
        if (bluetoothDeviceList1.size()==0){
            Toasty.info(mContext,"未发现可用设备").show();
            tvInfo.setText("未连接至设备");
            option.setText("连接");
        }
    }
    /**
     * 扫描设备---loop以下
     */
    public void removeHandlerMsg() {
        this.handler.removeCallbacksAndMessages((Object)null);
    }
    private List<Device> adapterShowList = new ArrayList<>();
    private void scanDevicesPeriod() {
        tvInfo.setText("搜索中...");
        map.clear();
        bluetoothDeviceList1.clear();
        adapterShowList.clear();
        startLeScan(scanCallback);
    }

    /*
    * 连接
    * */
    private void connect(final BluetoothDevice device) {
        showLoadingDialog(R.string.connect);
        tvInfo.setText("连接中...");
        targetDevice = device;
        if (callback!=null){
            liteBluetooth.removeGattCallback(callback);
        }
        liteBluetooth.connect(device, false, callback);
    }

    /**
     * scan first, then connect
     */
    private boolean isAutoConnect;//是否自动搜索并连接
    private void scanThenConnect() {
        if (leScanCallback!=null){
            liteBluetooth.stopScan(leScanCallback);
        }
        isAutoConnect = true;
        tvInfo.setText("搜索中...");
        initMacScanCallback();
        liteBluetooth.startLeScan(scanThenConnect);
    }

    private void initMacScanCallback(){
        scanThenConnect = new PeriodMacScanCallback(MAC, TIME_OUT_SCAN,true) {
            @Override
            public void onScanTimeout() {
                tvInfo.setText("未连接至设备");
                option.setText("连接");
            }

            @Override
            public void onDeviceFound(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                dissMissDialog();
                tvInfo.setText("连接中...");
                targetDevice = device;
                if (callback!=null){
                    liteBluetooth.removeGattCallback(callback);
                }
                liteBluetooth.connect(device, false, callback);
                if (scanThenConnect!=null){
                    liteBluetooth.stopScan(scanThenConnect);
                }
            }
        };
    }
    private void initScanCallback(){
        scanCallback = new BluetoothAdapter.LeScanCallback() {
            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                mDevice = device;
                //搜到的设备
                if (Math.abs(rssi) <= 95) {//过滤掉信号强度小于-95的设备
                    if (!map.containsValue(device)) {
                        bluetoothDeviceList1.add(device);
                        Log.i("----", device.getAddress());
                        if (deviceList.isEmpty()) {
                            Device newLink = new Device();
                            newLink.setMac(device.getAddress());
                            newLink.setName(device.getName() == null ? "默认名称" : device.getName());
                            newLink.setField1(DEVICE_DISCONNECTED);
                            adapterShowList.add(newLink);
                        } else {
                            boolean add = false;
                            for (Device device1 : deviceList) {
                                if (device1.getMac().equals(device.getAddress())) {
                                    adapterShowList.add(device1);
                                    add = true;
                                }
                            }
                            if (!add) {
                                Device newLink = new Device();
                                newLink.setMac(device.getAddress());
                                newLink.setName(device.getName() == null ? "默认名称" : device.getName());
                                newLink.setField1(DEVICE_DISCONNECTED);
                                adapterShowList.add(newLink);
                            }
                        }
                        showBles();
                    }
                    map.put(device.getAddress(), device);
                }
            }
        };
    }

    private PeriodMacScanCallback scanThenConnect;
    private BluetoothAdapter.LeScanCallback scanCallback;

    //连接
    private LiteBleGattCallback callback = new LiteBleGattCallback() {

        @Override
        public void onConnectSuccess(BluetoothGatt gatt, int status) {
            gatt.discoverServices();
        }

        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            dissMissDialog();
            targetDevice = gatt.getDevice();
            MAC = targetDevice.getAddress();
            isConnect = true;
            new Thread() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = CONNECT_SUCCESS;
                    MainActivity.this.handler.sendMessage(msg);
                }
            }.start();
        }

        @Override
        public void onConnectFailure(BleException exception) {
            dissMissDialog();
            Log.i("---scanThenConnect--", "连接失败");
            CONNECT_TYPE = 1;
            new Thread() {
                @Override
                public void run() {
                    Message msg = new Message();
                    msg.what = CONNECT_FAIL;
                    MainActivity.this.handler.sendMessage(msg);
                }
            }.start();
        }

        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
        }

        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {

        }

        @Override
        public void onCharacteristicWrite(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic, int status) {
            //当我们对ble设备写入相关数据成功后，这里也会被调用
            super.onCharacteristicWrite(gatt, characteristic, status);
        }
    };

    /**
     * get state
     */
    private void getBluetoothState() {
        BleLog.i(TAG, "liteBluetooth.getConnectionState: " + liteBluetooth.getConnectionState());
        BleLog.i(TAG, "liteBluetooth isInScanning: " + liteBluetooth.isInScanning());
        BleLog.i(TAG, "liteBluetooth isConnected: " + liteBluetooth.isConnected());
        BleLog.i(TAG, "liteBluetooth isServiceDiscoered: " + liteBluetooth.isServiceDiscoered());
        if (liteBluetooth.getConnectionState() >= LiteBluetooth.STATE_CONNECTING) {
            BleLog.i(TAG, "lite bluetooth is in connecting or connected");
        }
        if (liteBluetooth.getConnectionState() == LiteBluetooth.STATE_SERVICES_DISCOVERED) {
            BleLog.i(TAG, "lite bluetooth is in connected, services have been found");
        }
    }

    /**
     * 关闭连接
     */
    private void closeBluetoothGatt() {
        targetDevice = null;
        if (liteBluetooth.isConnectingOrConnected()) {
            if (liteBluetooth.getBluetoothGatt()!=null){
                liteBluetooth.getBluetoothGatt().disconnect();
                //liteBluetooth.getBluetoothGatt().close();
                tvInfo.setText("未连接至设备");
                option.setText("连接");
                isConnect = false;
            }
        }
    }

    /**
     * write data to characteristic
     */
    private void writeDataToCharacteristic(int type) {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector = connector.withUUIDString(UUID_SERVICE, UUID_CHAR_WRITE, null);
        boolean s = connector.writeCharacteristic(DeviceBytes.pack(false, 1, type), new BleCharactCallback() {
                    @Override
                    public void onSuccess(BluetoothGattCharacteristic characteristic) {
                        BleLog.i(TAG, "Write Success, DATA: " + Arrays.toString(characteristic.getValue()));
                    }

                    @Override
                    public void onFailure(BleException exception) {
                        BleLog.i(TAG, "Write failure: " + exception);
                    }
                });
        if (!s){
            Toasty.info(mContext,"未找到相应服务").show();
            return;
        }
    }

    //获取权限
    private void check() {
        //read phone state用于获取 imei 设备信息
        boolean phoneStatePermission =
                getPackageManager().checkPermission(READ_PHONE_STATE, getPackageName()) == PERMISSION_GRANTED;
       if (Build.VERSION.SDK_INT >= 23 &&  !phoneStatePermission ) {
            ActivityCompat.requestPermissions(this, new String[]{READ_PHONE_STATE,ACCESS_COARSE_LOCATION}, 0);
        } else {
            init();
        }
    }

    private boolean checkPermission(){
        boolean phoneStatePermission =
                getPackageManager().checkPermission(READ_PHONE_STATE, getPackageName()) == PERMISSION_GRANTED;
        boolean accessLocation =
                getPackageManager().checkPermission(ACCESS_COARSE_LOCATION, getPackageName()) == PERMISSION_GRANTED;
        if (Build.VERSION.SDK_INT >= 23 &&  !phoneStatePermission  ||!accessLocation ) {
            ActivityCompat.requestPermissions(this, new String[]{READ_PHONE_STATE,ACCESS_COARSE_LOCATION}, 0);
            return false;
        }
        return true;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            dissMissDialog();
            switch (msg.what) {
                case CONNECT_LOADING:
                    tvInfo.setText("连接中...");
                    break;
                case CONNECT_SUCCESS:
                    tvInfo.setText("已连接至\n" + dbLinkDevice.getName());
                    option.setText("断开");
                    addDevice();
                    break;
                case CONNECT_FAIL:
                    if (!liteBluetooth.getBluetoothAdapter().isEnabled()){
                        Toasty.info(mContext,"蓝牙不可用").show();
                    }else {
                        Toasty.info(mContext, "连接失败").show();
                    }
                    tvInfo.setText("未连接至设备");
                    option.setText("连接");
                    isConnect = false;
                    targetDevice = null;
                    break;
                case CONNECT_STUDY:
                    if (isClickUp && isClickDown && isConnect){
                        Log.i("----","    study");
                        writeDataToCharacteristic(1);
                    }
                    break;
            }
            if (msg.arg1==CONNECT_DEL && isClickUp && isClickLight && isConnect){
                Log.i("----","    update disconnect");
                writeDataToCharacteristic(5);
                updateDeviceByMac(MAC);
                deviceList.clear();
                deviceList.addAll(dao.loadAll());
            }
        }
    };

    /*
    * 权限申请回调
    * */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case 0:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    init();
                } else {
                    Toasty.info(mContext,"权限已被关闭，是否需要重新设置").show();
                    Intent intent = new Intent();
                    intent.setAction(Settings.ACTION_SETTINGS);
                    startActivity(intent);
                }
                return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    //权限申请失败则跳转至设置
    private void show() {
        final UIAlertView view = new UIAlertView(mContext, "温馨提示", "权限已被关闭，是否需要重新设置", "取消", "确定");
        view.setClicklistener(new UIAlertView.ClickListenerInterface() {
            @Override
            public void doLeft() {
                view.dismiss();
            }

            @Override
            public void doRight() {
                view.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }
        });
        view.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 1) {
            Toasty.info(mContext,"蓝牙已开启").show();
        }else {
            isConnect = false;
            option.setText("连接");
        }
    }

    @OnClick({R.id.kill, R.id.stop, R.id.anion,R.id.convection})
    public void menu(View view) {
        if (!checkPermission()){
            return;
        }
        if (!isConnect || targetDevice==null) {
            Toasty.info(mContext, "未连接蓝牙设备").show();
            return;
        }
        if (!liteBluetooth.getBluetoothAdapter().isEnabled()){
            initBle();
            return;
        }
        Log.i("----","   view id : "+view.getId());
        switch (view.getId()) {
            case R.id.kill:
                writeDataToCharacteristic(7);
                break;
            case R.id.stop:
                writeDataToCharacteristic(4);
                break;
            case R.id.anion:
                writeDataToCharacteristic(8);
                break;
            case R.id.convection://对流
                writeDataToCharacteristic(9);
                break;
            default:
                break;
        }
    }

    @OnClick(R.id.img_right)
    void right(){
        if (scanThenConnect!=null){
            liteBluetooth.stopScan(scanThenConnect);
        }
    }

    @OnClick(R.id.img_history)
    void history(){
        if (scanThenConnect!=null){
            liteBluetooth.stopScan(scanThenConnect);
        }
        SharePerferenceUtils.getIns(mContext).putBoolean(NOT_SCAN,true);
        intent = new Intent(mContext, HistoryActivity.class);
        startActivity(intent);
    }

    @OnClick(R.id.option)
    void option(View view) {
        if (!checkPermission()){
            return;
        }
        if (isConnect) {
            if (scanThenConnect!=null) {
                liteBluetooth.stopScan(scanThenConnect);
            }
            if (liteBluetooth.isConnectingOrConnected()) {
                liteBluetooth.removeGattCallback(callback);
                Log.i("----","  removeGattCallback(callback);");
            }
            closeBluetoothGatt();
        }else {
            if (!checkBlue()){
                Toasty.info(mContext, "该手机不支持BLE设备").show();
                return;
            }
            isAutoConnect = false;
            if (scanThenConnect!=null){
                liteBluetooth.stopScan(scanThenConnect);
                tvInfo.setText("搜索中...");
                option.setText("连接");
            }
            if (scanCallback!=null){
                liteBluetooth.stopScan(scanCallback);
                tvInfo.setText("搜索中...");
                option.setText("连接");
            }
            if (liteBluetooth.getBluetoothAdapter().isEnabled()){
                initDialogView();
                bluetoothDialogView.show();
                initScanCallback();
                scanDevicesPeriod();
            }else {
                initBle();
            }
        }
    }

    private boolean isClickUp,isClickDown,isClickLight;
    private void initView(){
        initDialogView();
        relativeParams = (RelativeLayout.LayoutParams) rMenu.getLayoutParams();
        relativeParams.leftMargin = 68;
        relativeParams.rightMargin = 68;
        rMenu.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) imgRight.getLayoutParams();
        relativeParams.height = (int) (0.056*h);
        relativeParams.width = relativeParams.height;
        imgRight.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) imgLogo.getLayoutParams();
        relativeParams.height = (int) (0.05*h);
        relativeParams.width = (int) (relativeParams.height*6.1);
        imgLogo.setLayoutParams(relativeParams);
        int menuH = (int) (0.17*h);
        int menuW = (int) (0.17*h*1.37);
        int topMargin = 12;
        relativeParams = (RelativeLayout.LayoutParams) light.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = (int) (0.03*h);
        light.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) kill.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = topMargin;
        kill.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) up.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = topMargin;
        up.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) stop.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = topMargin;
        stop.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) anion.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = topMargin;
        anion.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) down.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = topMargin;
        down.setLayoutParams(relativeParams);
        relativeParams = (RelativeLayout.LayoutParams) convection.getLayoutParams();
        relativeParams.height = menuH;
        relativeParams.width = menuW;
        relativeParams.topMargin = topMargin;
        convection.setLayoutParams(relativeParams);
        linerParams = (LinearLayout.LayoutParams) tvInfo.getLayoutParams();
        linerParams.height = (int) (0.08*h);
        linerParams.width = (int) (linerParams.height*2.76);
        tvInfo.setLayoutParams(linerParams);

        up.setOnTouchListener(touchListener);
        down.setOnTouchListener(touchListener);
        light.setOnTouchListener(touchListener);
    }

    float xDown,yDown,xUp,yUp,xLight,yLight;
    boolean isLongClickModule1,isLongClickModule2,isLongClickModule3;
    private boolean isStudy,isDel;
    private View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                switch (v.getId()) {
                    case R.id.up:
                        xUp = event.getX();
                        yUp = event.getY();
                        break;
                    case R.id.light:
                        xLight = event.getX();
                        yLight = event.getY();
                        break;
                    case R.id.down:
                        xDown = event.getX();
                        yDown = event.getY();
                        break;
                    default:
                        break;
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                if (!checkPermission()){
                    return false;
                }
                if (!isConnect || targetDevice == null) {
                    Toasty.info(mContext, "未连接蓝牙设备").show();
                    return false;
                }
                if (!liteBluetooth.getBluetoothAdapter().isEnabled()) {
                    initBle();
                    return false;
                }
                isDel = false;isStudy = false;
                switch (v.getId()){
                    case R.id.up:
                        if (!isClickUp) {
                            if (isLongClickModule2){
                                return false;
                            }
                            Log.i("----", "   Up");
                            writeDataToCharacteristic(2);
                        }else {isClickUp = false;}
                        isLongClickModule2 = false;
                        break;
                    case R.id.light:
                        if (!isClickLight) {
                            if (isLongClickModule1){
                                return false;
                            }
                            Log.i("----", "   Light");
                            writeDataToCharacteristic(6);
                        }else {isClickLight = false;}
                        isLongClickModule1 = false;
                        break;
                    case R.id.down:
                        if (!isClickDown) {
                            if (isLongClickModule3){
                                return false;
                            }
                            Log.i("----", "   Down");
                            writeDataToCharacteristic(3);
                        }else {isClickDown = false;}
                        isLongClickModule3 = false;
                        break;
                    default:
                        break;
                }
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                //检测是否长按,在非长按时检测
                //处理长按事件
                if (!isConnect || targetDevice == null) {
                    return false;
                }
                if (!liteBluetooth.getBluetoothAdapter().isEnabled()) {
                    return false;
                }
                switch (v.getId()) {
                    case R.id.light:
                        if (!isLongClickModule1){
                            isLongClickModule1 = isLongPressed(xLight, yLight, event.getX(),
                                    event.getY(), event.getDownTime(), event.getEventTime(), 600);
                        }
                        if (isLongClickModule1){
                            Log.i("----", "light   long");
                            isClickLight = true;
                        }
                        break;
                    case R.id.up:
                        if (!isLongClickModule2){
                            isLongClickModule2 = isLongPressed(xUp, yUp, event.getX(),
                                    event.getY(), event.getDownTime(), event.getEventTime(), 600);
                        }
                        if (isLongClickModule2){
                            Log.i("----", "up   long");
                            isClickUp = true;
                        }
                        break;
                    case R.id.down:
                        if (!isLongClickModule3){
                            isLongClickModule3 = isLongPressed(xDown, yDown, event.getX(),
                                    event.getY(), event.getDownTime(), event.getEventTime(), 600);
                        }
                        if (isLongClickModule3){
                            Log.i("----", "down   long");
                            isClickDown = true;
                        }
                        break;
                }
                final Message msg = new Message();
                if (isClickLight && isClickUp && !isDel){
                    isDel = true;
                    new Thread() {
                        @Override
                        public void run() {
                            msg.arg1 = CONNECT_DEL;
                            handler.sendMessage(msg);
                        }
                    }.start();
                    return true;
                }else if (isClickDown && isClickUp && !isStudy){
                    isStudy = true;
                    new Thread() {
                        @Override
                        public void run() {
                            msg.what = CONNECT_STUDY;
                            handler.sendMessage(msg);
                        }
                    }.start();
                    return true;
                }
            }
            return false;
        }
    };
    /* 判断是否有长按动作发生
    * @param lastX 按下时X坐标
    * @param lastY 按下时Y坐标
    * @param thisX 移动时X坐标
    * @param thisY 移动时Y坐标
    * @param lastDownTime 按下时间
    * @param thisEventTime 移动时间
    * @param longPressTime 判断长按时间的阀值
    */
    private boolean isLongPressed(float lastX,float lastY,
                                  float thisX,float thisY,
                                  long lastDownTime,long thisEventTime,
                                  long longPressTime){
        float offsetX = Math.abs(thisX - lastX);
        float offsetY = Math.abs(thisY - lastY);
        long intervalTime = thisEventTime - lastDownTime;
        if(offsetX <= 52 && offsetY <= 52 && intervalTime >= longPressTime){
            return true;
        }
        return false;
    }

    private List<Device> deviceList = new ArrayList<>();
    private boolean notScan;
    @Override
    protected void onResume() {
        super.onResume();
        if (mHomeWatcher==null) {
            mHomeWatcher = new HomeWatcher(this);
            mHomeWatcher.setOnHomePressedListener(new HomeWatcher.OnHomePressedListener() {
                @Override
                public void onHomePressed() {
                    SharePerferenceUtils.getIns(mContext).putBoolean(NOT_SCAN,false);
                    Log.i(TAG, "onHomePressed");
                    if (scanThenConnect!=null){
                        liteBluetooth.stopScan(scanThenConnect);
                        Log.i("----","  stopScan(scanThenConnect);");
                    }
                    if (scanCallback!=null){
                        liteBluetooth.stopScan(scanCallback);
                        Log.i("----","  stopScan(scanCallback);");
                    }
                    if (liteBluetooth.isConnectingOrConnected()) {
                        liteBluetooth.removeGattCallback(callback);
                        Log.i("----","  removeGattCallback(callback);");
                    }
                    closeBluetoothGatt();
                }
            });
        }
        mHomeWatcher.startWatch();//手机home键监听
        initBle();
        dao = BaseApp.getInstance().getDaoSession().getDeviceDao();
        deviceList.clear();
        deviceList.addAll(dao.loadAll());
        notScan = SharePerferenceUtils.getIns(mContext).getBoolean(NOT_SCAN,true);
        Log.i("----","  notScan: "+notScan);
        if (notScan){
            return;
        }
        if (isConnect){
            return;
        }
        if (!checkBlue()){
            Toasty.info(mContext, "该手机不支持BLE设备").show();
            return;
        }
        if (liteBluetooth.getBluetoothAdapter().isEnabled()){
            tvInfo.setText("搜索中...");
            map.clear();
            bluetoothDeviceList1.clear();
            adapterShowList.clear();
            initScanCallback();
            liteBluetooth.getBluetoothAdapter().startLeScan(leScanCallback);
        }
    }

    private BluetoothAdapter.LeScanCallback leScanCallback =  new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            mDevice = device;
            //搜到的设备
            if (Math.abs(rssi) <= 95) {//过滤掉信号强度小于-95的设备
                if (!map.containsValue(device)) {
                    for (Device device1 : deviceList) {
                        if (device1.getMac().equals(device.getAddress())) {
                            MAC = device.getAddress();
                            dbLinkDevice = device1;
                            Log.i("----db device",device.getAddress());
                            scanThenConnect();//扫描并连接
                            return;
                        }
                    }
                }
                map.put(device.getAddress(), device);
            }
        }
    };

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toasty.info(mContext, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                SharePerferenceUtils.getIns(mContext).putBoolean(NOT_SCAN,false);
                targetDevice = null;
                if (scanThenConnect!=null) {
                    liteBluetooth.stopScan(scanThenConnect);
                }
                if (scanCallback!=null) {
                    liteBluetooth.stopScan(scanCallback);
                }
                if (liteBluetooth.isConnectingOrConnected()) {
                    liteBluetooth.removeGattCallback(callback);
                }
                if (liteBluetooth.isConnectingOrConnected()) {
                    if (liteBluetooth.getBluetoothGatt()!=null) {
                        liteBluetooth.getBluetoothGatt().disconnect();
                        isConnect = false;
                    }
                }
                EventBus.getDefault().post(new ExitApp());
                System.exit(1);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onEvent(DoOption option) {
        if (option.updateName&&isConnect&&targetDevice.getAddress().equals(option.mac)){
            tvInfo.setText("已连接至\n"+option.name);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("----","onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("----","onStop");
        if (isConnect) {
            SharePerferenceUtils.getIns(mContext).putBoolean(NOT_SCAN, false);
        }
        mHomeWatcher.stopWatch();// 在onPause中停止监听，不然会报错的。
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("---","onDestroy");
    }
}
